#
# Copyright Thoughtworks, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

class Admin::ConfigurationController < AdminController
  before_action :check_admin_user_and_403
  before_action :fetch_config, :only => [:update]

  def update
    result = HttpLocalizedOperationResult.new
    config_validity = admin_service.updateConfig(params[:go_config], result)
    
    if config_validity.isValid()
      flash[:success] = config_validity.wasMerged() ? "Saved successfully. The configuration was modified by someone else, but your changes were merged successfully." : 'Saved successfully.'
      render json: { success: true, message: flash[:success] }
    else
      render json: { success: false, error: config_validity.errorMessage() }, status: :unprocessable_entity
    end
  end

  private
  def fetch_config
    config = go_config_service.getConfigAtVersion('current')
    @go_config = GoConfig.new({location: go_config_service.fileLocation, md5: config.getMd5, content: config.getContent})
  end
end

